package org.dkakunsi.aplikasitoko.data.adapter;

import java.util.List;

import org.dkakunsi.aplikasitoko.data.access.PelakuDataAccess;
import org.dkakunsi.aplikasitoko.data.entity.Pelaku;
import org.dkakunsi.aplikasitoko.data.util.ApplicationDataException;
import org.dkakunsi.aplikasitoko.data.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class PelakuDataAdapter implements PelakuDataAccess {
	
	private Session session;
	private Transaction tx;
	
	public PelakuDataAdapter() {
		this.session = HibernateUtil.openSession();
		this.tx = session.beginTransaction();
	}
	
	public PelakuDataAdapter(Session session) {
		this.session = session;
		this.tx = session.beginTransaction();
	}

	@Override
	public void save(Object object) throws ApplicationDataException {
		Pelaku pelaku = null;
		
		try {
			pelaku = (Pelaku) object;
			
			session.save(pelaku);
			tx.commit();
		} catch(ConstraintViolationException x) {
			throw new ApplicationDataException("Duplikasi data untuk KODE : " +pelaku.getKode());
		}
	}

	@Override
	public void update(Object object) throws Exception {
		Pelaku pelaku = (Pelaku) object;
		
		session.merge(pelaku);
		tx.commit();
	}

	@Override
	public void delete(Object object) throws Exception {
		Pelaku pelaku = (Pelaku) object;
		
		session.delete(pelaku);
		tx.commit();
	}

	@Override
	public Object getByID(String id) throws ApplicationDataException {
		Pelaku pelaku = (Pelaku) session.get(Pelaku.class, id);
		tx.commit();

		if(pelaku != null){
			return pelaku;
		} else {
			throw new ApplicationDataException("File Not Found");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<org.dkakunsi.aplikasitoko.data.entity.Pelaku> getAll(String type) throws Exception {
		List<Pelaku> all = null;
		
		Session session = HibernateUtil.openSession();
		
		if(type.equals("PELAKU")){
			all = session.createQuery("from Pelaku order by KODE").list();			
		} else if(type.equals("LOG")){
			all = session.createQuery("from Log order by KODE").list();			
		} else if(type.equals("SUPPLIER")){
			all = session.createQuery("from Supplier order by KODE").list();			
		}

		return all;
	}

	@Override
	public Session getSession() {
		return this.session;
	}

	@Override
	public Object getBy(String nama) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
